package com.ycsj.goldmedalnewconcept.common.jpush;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.text.TextUtils;
import android.util.Log;

import com.ycsj.common.base.SpKeys;
import com.ycsj.common.utils.GsonUtil;
import com.ycsj.common.utils.SPUtil;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.parent.activity.ParentsLeaveListActivity;
import com.ycsj.goldmedalnewconcept.parent.activity.ParentsRedPackageListActivity;
import com.ycsj.goldmedalnewconcept.student.activity.MyHomeWorkActivity;
import com.ycsj.goldmedalnewconcept.student.activity.StudentMainActivity;
import com.ycsj.goldmedalnewconcept.student.activity.StudentMyHomeActivity;
import com.ycsj.goldmedalnewconcept.teacher.activity.TeacherAttendanceManagerActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Iterator;

import cn.jpush.android.api.JPushInterface;

//import android.app.Notification;
//import android.app.NotificationManager;
//import android.app.PendingIntent;
//import android.content.BroadcastReceiver;
//import android.content.Context;
//import android.content.Intent;
//import android.net.Uri;
//import android.os.Bundle;
//import android.support.v4.app.NotificationCompat;
//import android.text.TextUtils;
//import android.util.Log;
//
//import com.ssyc.common.base.SpKeys;
//import com.ssyc.common.manager.AccountUtils;
//import com.ssyc.common.utils.GsonUtil;
//import com.ssyc.common.utils.SPUtil;
//import com.ssyc.goldstudyking.R;
//import com.ssyc.gsk_parents.activity.ParentsBabyHomeWorkActivity;
//import com.ssyc.gsk_parents.activity.ParentsLeaveListActivity;
//import com.ssyc.gsk_teacher.activity.TeacherRatifyLeaveListActivity;
//import com.ssyc.gsk_teacher.activity.TeacherStudentAcceptBirthdayActivity;
//import com.ssyc.gsk_teacher_appraisal.activity.TkStudentrAppraisalMainActivity;
//import com.ssyc.student.activity.StudentHomeWorkActivity;
//
//import org.json.JSONException;
//import org.json.JSONObject;
//
//import java.util.Iterator;
//
//import cn.jpush.android.api.JPushInterface;
//
///**
// * 自定义接收器
// * <p>
// * 如果不定义这个 Receiver，则： 1) 默认用户会打开主界面 2) 接收不到自定义消息
// */
public class MyReceiver extends BroadcastReceiver {
    private static final String TAG = "test";


    //推送的内容
    String content;

    //推送的标题
    String title;
    String json;


    @Override
    public void onReceive(Context context, Intent intent) {
        try {
            Bundle bundle = intent.getExtras();

            if (JPushInterface.ACTION_REGISTRATION_ID
                    .equals(intent.getAction())) {
                String regId = bundle
                        .getString(JPushInterface.EXTRA_REGISTRATION_ID);
                Log.i(TAG, "[MyReceiver] 接收Registration Id : " + regId);
                SPUtil.put(context, SpKeys.JPUSH_ID, regId);

            } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent
                    .getAction())) {

                Log.i(TAG, "[MyReceiver] 接收到推送下来的自定义消息: "
                        + bundle.getString(JPushInterface.EXTRA_MESSAGE));


                //推送的内容
                content = bundle.getString(JPushInterface.EXTRA_MESSAGE);

                //推送的标题
                title = bundle.getString(JPushInterface.EXTRA_TITLE);
                json = bundle.getString(JPushInterface.EXTRA_EXTRA);

                SPUtil.put(context, SpKeys.TITLE, title);
                SPUtil.put(context, SpKeys.CONTENT, context);
                SPUtil.put(context, SpKeys.JSON, json);

                Log.i("test", "标题是:" + title + "---内容是:" + content + "---json是:" + json);

                //自定义消息通知
                receivingNotification(context, bundle);


            } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED
                    .equals(intent.getAction())) {

                Log.i(TAG, "[MyReceiver] 接收到推送下来的通知");

                int notifactionId = bundle
                        .getInt(JPushInterface.EXTRA_NOTIFICATION_ID);
                Log.i(TAG, "[MyReceiver] 接收到推送下来的通知的ID: " + notifactionId);


            } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent
                    .getAction())) {

                Log.i(TAG, "[MyReceiver] 用户点击打开了通知");

                String json = SPUtil.getString(context, SpKeys.JSON);
                String content = SPUtil.getString(context, SpKeys.CONTENT);
                Log.i("test",  "---内容是:" + content + "---json是:" + json);

                //创建跳转的intent
                Intent it = null;

                // 通知行为（点击后能进入应用界面）
                if (!TextUtils.isEmpty(json)) {
                    PushInfo pushInfo = GsonUtil.jsonToBean(json, PushInfo.class);
                    //type由数字$和班级号(有可能没有,有可能有)组成
                    String type = pushInfo.type;
                    //使用$符号进行切割   0=生日，1=题库练习，2=新练习, 3=催练习, 4=重新布置练习
                    String[] arrs = type.split("#");
                    String index = arrs[0];

                    if ("0".equals(index)) {
                        //生日
                        it = new Intent(context, StudentMainActivity.class);
                    } else if ("1".equals(index)) {
                        //题库练习
                        it = new Intent(context, MyHomeWorkActivity.class);

                    } else if ("2".equals(index)) {
                        //新练习
                       it = new Intent(context, MyHomeWorkActivity.class);

                    } else if ("3".equals(index)) {
                        //催练习
                       it = new Intent(context, MyHomeWorkActivity.class);

                    } else if ("4".equals(index)) {
                        //重新布置练习
                        it = new Intent(context, MyHomeWorkActivity.class);

                    } else if ("5".equals(index)) {
                        //老师审批家长申请的请假条
                        it = new Intent(context, TeacherAttendanceManagerActivity.class);
                        it.putExtra("classnum",arrs[1]);
                        it.putExtra("date",arrs[2]);

                    } else if ("6".equals(index)) {
                        //家长批准请假条

                        it = new Intent(context, ParentsLeaveListActivity.class);

                    }  else if ("7".equals(index)) {
                        //系统领取牛奶提醒
                        it = new Intent(context, StudentMyHomeActivity.class);

                    } else if ("8".equals(index)) {
                        //牛奶即将过期提醒
                        it = new Intent(context, StudentMyHomeActivity.class);

                    } else if ("9".equals(index)) {
                        //红包即将过期
                        it = new Intent(context, ParentsRedPackageListActivity.class);

                    }else if ("10".equals(index)) {
                        //宠物升级
                        it = new Intent(context, StudentMyHomeActivity.class);

                    }else if ("11".equals(index)) {
                        //道具题型
                        it = new Intent(context, StudentMyHomeActivity.class);

                    }else if (content.contains("http")) {

                    }
                }

                // 打开自定义的Activity
                it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
                        Intent.FLAG_ACTIVITY_CLEAR_TOP);
                context.startActivity(it);

            } else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent
                    .getAction())) {
                Log.d(TAG,
                        "[MyReceiver] 用户收到到RICH PUSH CALLBACK: "
                                + bundle.getString(JPushInterface.EXTRA_EXTRA));
                // 在这里根据 JPushInterface.EXTRA_EXTRA 的内容处理代码，比如打开新的Activity，
                // 打开一个网页等..

            } else if (JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent
                    .getAction())) {
                boolean connected = intent.getBooleanExtra(
                        JPushInterface.EXTRA_CONNECTION_CHANGE, false);
                Log.w(TAG, "[MyReceiver]" + intent.getAction()
                        + " connected state change to " + connected);
            } else {
                Log.d(TAG,
                        "[MyReceiver] Unhandled intent - " + intent.getAction());
            }
        } catch (Exception e) {

        }
    }

    // 打印所有的 intent extra 数据
    private static String printBundle(Bundle bundle) {
        StringBuilder sb = new StringBuilder();
        for (String key : bundle.keySet()) {
            if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getInt(key));
            } else if (key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getBoolean(key));
            } else if (key.equals(JPushInterface.EXTRA_EXTRA)) {
                if (TextUtils.isEmpty(bundle
                        .getString(JPushInterface.EXTRA_EXTRA))) {
                    Log.i(TAG, "This message has no Extra data");
                    continue;
                }

                try {
                    JSONObject json = new JSONObject(
                            bundle.getString(JPushInterface.EXTRA_EXTRA));
                    Iterator<String> it = json.keys();

                    while (it.hasNext()) {
                        String myKey = it.next();
                        sb.append("\nkey:" + key + ", value: [" + myKey + " - "
                                + json.optString(myKey) + "]");
                    }
                } catch (JSONException e) {
                    Log.e(TAG, "Get message extra JSON error!");
                }

            } else {
                sb.append("\nkey:" + key + ", value:" + bundle.getString(key));
            }
        }
        return sb.toString();
    }


    private void receivingNotification(Context context, Bundle bundle) {

        //推送的内容
        String content = bundle.getString(JPushInterface.EXTRA_MESSAGE);

        //推送的标题
        String title = bundle.getString(JPushInterface.EXTRA_TITLE);
        String json = bundle.getString(JPushInterface.EXTRA_EXTRA);


        Log.i("test", "content=" + content + "title=" + title + "json=" + json);

        //创建跳转的intent
        Intent intent = null;

        // 通知行为（点击后能进入应用界面）
//        if (!TextUtils.isEmpty(json)) {
//            PushInfo pushInfo = GsonUtil.jsonToBean(json, PushInfo.class);
//            //type由数字$和班级号(有可能没有,有可能有)组成
//            String type = pushInfo.type;
//            //使用$符号进行切割
//            String[] arrs = type.split("#");
//            String index = arrs[0];
//
//            if ("4".equals(index)) {
//                //家长端收到请假是否批准,跳到家长端请假列表界面,不需要携带班级号
////                intent = new Intent(context, ParentsLeaveListActivity.class);
//
//            } else if ("5".equals(index)) {
//
//            } else if ("1".equals(index)) {
//                //一般网页
//
//            } else if ("2".equals(index)) {
//                //学生收到题库练习推送,不需要携带班级
////                intent = new Intent(context, StudentHomeWorkActivity.class);
//
//            } else if ("3".equals(index)) {
//                //学生和家长收到老师生日祝福,不需要携带班级
////                intent = new Intent(context, TeacherStudentAcceptBirthdayActivity.class);
////                intent.putExtra("birthady", content);
//
//            } else if ("6".equals(index)) {
//                //学生收到老师的自定义练习推送,不需要携带班级
////                if ("0".equals(AccountUtils.getRole(context))) {
////                    //学生练习
////                    intent = new Intent(context, StudentHomeWorkActivity.class);
////                } else if ("0".equals(AccountUtils.getRole(context))) {
////                    //家长练习
////                    intent = new Intent(context, ParentsBabyHomeWorkActivity.class);
////                }
//
//            } else if ("7".equals(index)) {
//                //其它
//            } else if (content.contains("http")) {
//                //跳转浏览器
//                Intent in = new Intent(Intent.ACTION_VIEW, Uri
//                        .parse(content));
//                context.startActivity(in);
//            }
//        }


        // 使用广播或者通知进行内容的显示
        NotificationCompat.Builder builder = new NotificationCompat.Builder(
                context);

        //设置标题,内容以及小图标
        builder.setContentText(content)
                .setSmallIcon(R.drawable.ic_launcher_img)
                .setContentTitle(title);

        //收到通知一般有三种用户提示方式：声音，震动，呼吸 灯
        builder.setDefaults(Notification.DEFAULT_SOUND);

        //设置点击之后消失
        builder.setAutoCancel(true);

        if (null != intent) {
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
            PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
                    intent, PendingIntent.FLAG_UPDATE_CURRENT);
            builder.setContentIntent(pendingIntent);

        } else {
            return;
        }

        NotificationManager manager = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);
        manager.notify(1, builder.build());
    }
}
